package cn.sw.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.sw.api.system.menu.MenuApi;
import cn.sw.auth.entity.AuthInfo;
import cn.sw.auth.entity.UserInfo;
import cn.sw.auth.entity.UserParameter;
import cn.sw.auth.granter.IUserInfoGranter;
import cn.sw.auth.granter.TokenGranter;
import cn.sw.auth.granter.UserInfoGranterBuilder;
import cn.sw.common.database.domain.dto.form.MenuFormDto;
import cn.sw.common.database.domain.entity.Menu;
import cn.sw.common.entity.GrantType;
import cn.sw.common.entity.R;
import cn.sw.common.http.HttpResponse;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@AllArgsConstructor
@RequestMapping("/auth")
//@Api(value = "用户授权认证", tags = "授权接口")
public class AuthController {
    @Resource
    MenuApi menuApi;
    @GetMapping("test2/{id}")
    public HttpResponse<?> test2(@PathVariable("id") String id) {
        System.out.println("222222222");
        return menuApi.RById(id);
    }

    @PostMapping("test3")
    public HttpResponse<?> test3(@RequestBody MenuFormDto form) {
        System.out.println("3333333333");
        return menuApi.C(form);
    }

    @GetMapping("test")
    public String test() {
        System.out.println("11111111111111111111111111");
        return "test";
    }

    @PostMapping("token")
    public R<?> doLogin(@ApiParam(value = "授权类型", required = true) @RequestParam(defaultValue = "PASSWORD", required = false) GrantType grantType,
                        @ApiParam(value = "租户ID", required = true) @RequestParam(defaultValue = "000000", required = false) String tenantId,
                        @ApiParam(value = "账号") @RequestParam(required = false) String account,
                        @ApiParam(value = "密码") @RequestParam(required = false) String password) throws Exception {

        UserParameter userParameter = UserParameter.builder()
                .tenantId(tenantId)
                .account(account)
                .password(password)
                .grantType(grantType)
                .build();

        //策略模式,兼容不同的登陆方式
        IUserInfoGranter userInfoGranter = UserInfoGranterBuilder.getUserInfoGranter(grantType);
        UserInfo userInfo = userInfoGranter.grant(userParameter);
        if (userInfo == null || userInfo.getUser() == null || userInfo.getUser().getId() == null) {
            return R.fail("用户名或密码错误");
        }

        return R.ok(TokenGranter.createAuthInfo(userInfo));
    }

    // 查询登录状态，浏览器访问： http://localhost:8081/user/isLogin
    @RequestMapping("isLogin")
    public String isLogin() {
        return "当前会话是否登录：" + StpUtil.isLogin();
    }
}
